package com.hck.infrastructure.persistent.repository;

import com.hck.domain.doctor.model.entity.DoctorEntity;
import com.hck.domain.doctor.repository.IDoctorRepository;
import com.hck.infrastructure.persistent.dao.IDoctorDao;
import com.hck.infrastructure.persistent.po.Doctor;
import com.hck.infrastructure.redis.IRedisService;
import com.hck.types.common.Constants;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * IDoctorRepository class description here.
 *
 * @author 黄朝看
 * @date 2025/7/2
 */
@Repository
public class DoctorRepository implements IDoctorRepository {

    @Resource
    private IDoctorDao doctorDao;

    @Resource
    private IRedisService redisService;

    @Override
    public DoctorEntity findByLoginName(String loginName) {
        Doctor doctor = doctorDao.getByLoginName(loginName);
        return convertToDomain(doctor);
    }

    @Override
    public void update(DoctorEntity entity) {
        Doctor doctor = convertToPo(entity);
        doctorDao.update(doctor);
    }

    @Override
    public DoctorEntity getDoctorInfo(Long doctorId) {
        Doctor doctor = doctorDao.getById(doctorId);
        return convertToDomain(doctor);
    }

    @Override
    public List<DoctorEntity> findAll() {
        String cacheKey = Constants.DOCTOR_LIST_KEY;
        List<DoctorEntity> list = redisService.getValue(cacheKey);
        if(list != null)
            return list;

        List<Doctor> doctorList = doctorDao.selectAll();
        list = new ArrayList<>();
        if (doctorList != null) {
            for (Doctor doctor : doctorList) {
                DoctorEntity entity = new DoctorEntity();
                BeanUtils.copyProperties(doctor, entity);
                list.add(entity);
            }
        }

        redisService.setValue(cacheKey,list);
        return list;
    }

    private DoctorEntity convertToDomain(Doctor doctor){
        if(doctor == null)
            return null;
        DoctorEntity entity = new DoctorEntity();
        BeanUtils.copyProperties(doctor,entity);
        return entity;
    }

    private Doctor convertToPo(DoctorEntity entity){
        if(entity == null)
            return null;

        Doctor doctor = new Doctor();
        BeanUtils.copyProperties(entity,doctor);
        return doctor;
    }
}
